package com.hwpt.chesedemo.presentation.viewmodel

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.hwpt.chesedemo.data.remote.llm.AiService
import com.hwpt.chesedemo.data.remote.llm.PromptTemplates
import com.hwpt.chesedemo.data.local.entity.GameRecordEntity
import com.hwpt.chesedemo.data.local.repository.ChessRepository
import com.hwpt.chesedemo.presentation.theme.AppStrings
import com.hwpt.chesedemo.presentation.theme.LanguageManager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class EvaluationViewModel @Inject constructor(
    private val repository: ChessRepository,
    private val aiService: AiService
) : ViewModel() {

    var state by mutableStateOf(EvaluationState())
        private set

    private val gson = Gson()

    // 当前语言环境的字符串资源
    private val currentStrings
        get() = AppStrings.getByLanguageCode(LanguageManager.currentLanguageCode)

    // 当前语言代码
    private val currentLanguageCode: String
        get() = LanguageManager.currentLanguageCode

    init {
        loadGameRecords()
    }

    private fun loadGameRecords() {
        viewModelScope.launch {
            repository.getSavedGames().collectLatest { records ->
                // 只转换记录中的AI难度名称和游戏结果，不转换AI分析结果
                val translatedRecords = records.map { record ->
                    record.copy(
                        aiDifficulty = translateDifficultyName(record.aiDifficulty ?: ""),
                        result = translateGameResult(record.result ?: "")
                    )
                }
                state = state.copy(gameRecords = translatedRecords)
            }
        }
    }

    /**
     * 将中文难度名称转换为当前语言的难度名称
     */
    private fun translateDifficultyName(chineseName: String): String {
        return AppStrings.translateDifficultyName(chineseName, currentStrings)
    }

    /**
     * 将游戏结果转换为当前语言
     */
    private fun translateGameResult(result: String): String {
        return AppStrings.translateGameResult(result, currentStrings)
    }

    fun onInputMethodSelected(method: InputMethod) {
        state = state.copy(selectedInputMethod = method)
        updateAnalyzeButtonState()
    }

    fun onRecordSelected(record: GameRecordEntity) {
        // 确保选中的记录也已转换难度名称和游戏结果
        val translatedRecord = record.copy(
            aiDifficulty = translateDifficultyName(record.aiDifficulty ?: ""),
            result = translateGameResult(record.result ?: "")
        )
        state = state.copy(selectedRecord = translatedRecord)
        updateAnalyzeButtonState()
    }

    fun onPgnTextChanged(text: String) {
        state = state.copy(pgnText = text)
        updateAnalyzeButtonState()
    }

    fun onAnalyze() {
        state = state.copy(isLoading = true, showResults = false)

        viewModelScope.launch {
            try {
                // 获取PGN数据
                val pgn = when (state.selectedInputMethod) {
                    InputMethod.RECORD -> state.selectedRecord?.pgn ?: ""
                    InputMethod.TEXT -> state.pgnText
                }

                if (pgn.isBlank()) {
                    state = state.copy(
                        isLoading = false,
                        errorMessage = currentStrings.pastePgnFormat
                    )
                    return@launch
                }

                // 构建评估问题，传入当前语言代码
                val question = PromptTemplates.buildEvaluationQuestion(pgn, currentLanguageCode)

                // 调用AI服务进行水平评估
                val aiResponse = aiService.aiEvaluation(question)

                // 解析AI响应，保持AI返回的原始语言
                val evaluationResult = parseAiEvaluationResponse(aiResponse)

                state = state.copy(
                    isLoading = false,
                    showResults = true,
                    whiteElo = evaluationResult.whiteElo,
                    blackElo = evaluationResult.blackElo,
                    whiteAccuracy = evaluationResult.whiteAccuracy,
                    blackAccuracy = evaluationResult.blackAccuracy,
                    whiteBlunders = evaluationResult.whiteBlunders,
                    blackBlunders = evaluationResult.blackBlunders,
                    whiteMistakes = evaluationResult.whiteMistakes,
                    blackMistakes = evaluationResult.blackMistakes,
                    whiteInaccuracies = evaluationResult.whiteInaccuracies,
                    blackInaccuracies = evaluationResult.blackInaccuracies,
                    // 保持AI返回的原始gameResult和gameQuality，不进行语言转换
                    gameResult = evaluationResult.gameResult,
                    gameQuality = evaluationResult.gameQuality,
                    errorMessage = null
                )

            } catch (e: Exception) {
                state = state.copy(
                    isLoading = false,
                    errorMessage = "${currentStrings.analyzing} ${currentStrings.loss}: ${e.message}",
                    showResults = false
                )
            }
        }
    }

    /**
     * 解析AI的评估响应
     */
    private fun parseAiEvaluationResponse(aiResponse: String): EvaluationResult {
        return try {
            // 首先尝试直接解析JSON
            val result = gson.fromJson(aiResponse, RawEvaluationResult::class.java)
            convertToEvaluationResult(result)
        } catch (e: JsonSyntaxException) {
            // 如果直接解析失败，尝试从响应文本中提取JSON
            val jsonMatch = Regex("\\{.*\\}", RegexOption.DOT_MATCHES_ALL).find(aiResponse)
            if (jsonMatch != null) {
                try {
                    val result = gson.fromJson(jsonMatch.value, RawEvaluationResult::class.java)
                    convertToEvaluationResult(result)
                } catch (e2: JsonSyntaxException) {
                    // 如果还是失败，返回默认值
                    getDefaultEvaluationResult()
                }
            } else {
                // 如果没有找到JSON，返回默认值
                getDefaultEvaluationResult()
            }
        } catch (e: Exception) {
            getDefaultEvaluationResult()
        }
    }

    data class RawEvaluationResult(
        val whiteElo: Int = 0,
        val blackElo: Int = 0,
        val whiteAccuracy: Double = 0.0,
        val blackAccuracy: Double = 0.0,
        val whiteBlunders: Int = 0,
        val blackBlunders: Int = 0,
        val whiteMistakes: Int = 0,
        val blackMistakes: Int = 0,
        val whiteInaccuracies: Int = 0,
        val blackInaccuracies: Int = 0,
        val gameResult: String = "",
        val gameQuality: String = ""
    )

    // 转换方法
    private fun convertToEvaluationResult(raw: RawEvaluationResult): EvaluationResult {
        return EvaluationResult(
            whiteElo = raw.whiteElo,
            blackElo = raw.blackElo,
            whiteAccuracy = (raw.whiteAccuracy * 100).toInt(),
            blackAccuracy = (raw.blackAccuracy * 100).toInt(),
            whiteBlunders = raw.whiteBlunders,
            blackBlunders = raw.blackBlunders,
            whiteMistakes = raw.whiteMistakes,
            blackMistakes = raw.blackMistakes,
            whiteInaccuracies = raw.whiteInaccuracies,
            blackInaccuracies = raw.blackInaccuracies,
            // 保持AI返回的原始gameResult和gameQuality，不进行语言转换
            gameResult = raw.gameResult,
            gameQuality = raw.gameQuality
        )
    }

    /**
     * 获取默认的评估结果（当AI解析失败时使用）
     */
    private fun getDefaultEvaluationResult(): EvaluationResult {
        return EvaluationResult(
            whiteElo = 0,
            blackElo = 0,
            whiteAccuracy = 0,
            blackAccuracy = 0,
            whiteBlunders = 0,
            blackBlunders = 0,
            whiteMistakes = 0,
            blackMistakes = 0,
            whiteInaccuracies = 0,
            blackInaccuracies = 0,
            // 使用原始字符串，不进行语言转换
            gameResult = ""
        )
    }

    private fun updateAnalyzeButtonState() {
        val isEnabled = when (state.selectedInputMethod) {
            InputMethod.RECORD -> state.selectedRecord != null
            InputMethod.TEXT -> state.pgnText.isNotBlank()
        }
        state = state.copy(isAnalyzeEnabled = isEnabled)
    }
}

// 修改EvaluationResult为数据类，使其可被Gson解析
data class EvaluationResult(
    val whiteElo: Int = 0,
    val blackElo: Int = 0,
    val whiteAccuracy: Int = 0,
    val blackAccuracy: Int = 0,
    val whiteBlunders: Int = 0,
    val blackBlunders: Int = 0,
    val whiteMistakes: Int = 0,
    val blackMistakes: Int = 0,
    val whiteInaccuracies: Int = 0,
    val blackInaccuracies: Int = 0,
    val gameResult: String = "",
    val gameQuality: String = ""
)

// 其他数据类和枚举保持不变
data class EvaluationState(
    val selectedInputMethod: InputMethod = InputMethod.RECORD,
    val gameRecords: List<GameRecordEntity> = emptyList(),
    val selectedRecord: GameRecordEntity? = null,
    val pgnText: String = "",
    val isAnalyzeEnabled: Boolean = false,
    val isLoading: Boolean = false,
    val showResults: Boolean = false,
    val whiteElo: Int = 0,
    val blackElo: Int = 0,
    val whiteAccuracy: Int = 0,
    val blackAccuracy: Int = 0,
    val whiteBlunders: Int = 0,
    val blackBlunders: Int = 0,
    val whiteMistakes: Int = 0,
    val blackMistakes: Int = 0,
    val whiteInaccuracies: Int = 0,
    val blackInaccuracies: Int = 0,
    val gameResult: String = "",
    val gameQuality: String = "",
    val errorMessage: String? = null
)